package com.roc.service.impl;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.roc.bean.MenuBean;
import com.roc.dao.DaoException;
import com.roc.dao.IAuditingItemDao;
import com.roc.dao.IBaseDao;
import com.roc.dao.impl.BaseDaoImpl;
import com.roc.dao.operator.IPowerInfoDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.AuditingItem;
import com.roc.pojo.MerchantModuleRight;
import com.roc.pojo.MessageSend;
import com.roc.pojo.Module;
import com.roc.pojo.ModuleCategory;
import com.roc.pojo.OperRole;
import com.roc.pojo.Operators;
import com.roc.pojo.SysLog;
import com.roc.pojo.TblArea;
import com.roc.pojo.TblOrgMain;
import com.roc.pojo.TblTerActivateStatistics;
import com.roc.service.IAgentService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.DateTime;
import com.roc.util.MD5Utils;
import com.roc.util.Utils;
import com.roc.util.constant.AuditingResultCodeType;
import com.roc.util.constant.AuditingType;
import com.roc.util.constant.Constant;
import com.roc.util.constant.DateFormat;
import com.roc.util.constant.MerinfoModule;
import com.roc.util.constant.OperatorsStatus;
import com.roc.util.constant.Role;
import com.roc.util.constant.SysLogType;

/**
 * 
 * @author 陈锴
 * 
 * 操作员权限管理
 *
 */

@Service
@Transactional
@SuppressWarnings("all")
public class PowerInfoServiceImpl  implements IPowerInfoService {
	
	static Logger logger=LogManager.getLogger(PowerInfoServiceImpl.class);
	
	@Autowired
	private IPowerInfoDao powerInfoDao;
	@Autowired
	private IAuditingItemDao auditingItemDao;
	@Autowired
	private IBaseDao baseDao;
	@Autowired
	private IPageDao pageDao;
	@Autowired
	private IAgentService agentService;

	@Override
	public boolean editUpdateOperatorPowerService(String accountNo,String operators,
			String[] list,String type) throws ServiceException {
		boolean result=false;
		try {
			//删除相关权限
			powerInfoDao.removeModuleOperator(accountNo,type);
			 
			//添加操作日志
			baseDao.addSyslog(SysLogType.POWERINFO_DELETE.getCode(), SysLogType.POWERINFO_DELETE.getName(), accountNo, "操作员"+operators+"删除【"+accountNo+"】所有权限成功!");
			
			//重新赋予新的权限
			if(null != list && list.length > 0 ){
				if(null != type && type.equals("0")){//数据分析系统
					operators=Constance.ANALY_ADMIN;//数据分析系统当前操作人员默认是"admin"
				} 
				for (int i = 0; i < list.length; i++) {
					MerchantModuleRight module=new MerchantModuleRight();				
					module.setModuleCode(list[i]);
					module.setMerchantNo(accountNo);
					module.setOperators(operators);
					powerInfoDao.editSave(module);
					baseDao.addSyslog(SysLogType.POWERINFO_ADD.getCode(), SysLogType.POWERINFO_ADD.getName(), accountNo, "操作员"+operators+"添加【"+list[i]+"】权限成功!");
				}
			}
			result=true;
		} catch (DaoException e) {
			throw new ServiceException("操作操作员权限失败！ ");
		}
		
		return result;
	}

	@Override
	public List<ModuleCategory> queryModuleCategoryList(Operators logingOperators,String type)
			throws ServiceException {
		List<MenuBean> menuBeanList=null;
		List<ModuleCategory> moduleCategoryList=new ArrayList<ModuleCategory>();
		Map<String,ModuleCategory> categoryMenuMap=new TreeMap<String,ModuleCategory>();
		
		try {
			menuBeanList=powerInfoDao.queryModuleCategoryList(logingOperators,type);
			
			ModuleCategory temp=new ModuleCategory();
			ModuleCategory moduleCategory=null;
			
			for(MenuBean bean:menuBeanList){
				
				String moduleCotegoryCode=bean.getCategoryCode();
				if(!moduleCotegoryCode.equals(temp.getModuleCategoryCode())){
					moduleCategory=new ModuleCategory();
					temp.setModuleCategoryCode(bean.getCategoryCode());
					temp.setModuleCategoryName(bean.getCategoryName());
					
					moduleCategory.setModuleCategoryCode(bean.getCategoryCode());
					moduleCategory.setModuleCategoryName(bean.getCategoryName());
					
					Module module=new Module();
					module.setModuleCode(bean.getModuleCode());
					module.setModuleName(bean.getModuleName());
					module.setModuleAct(bean.getModuleAct());
					
					moduleCategory.getModules().add(module);
					categoryMenuMap.put(moduleCotegoryCode, moduleCategory);
				}else{
					Module module=new Module();
					module.setModuleCode(bean.getModuleCode());
					module.setModuleName(bean.getModuleName());
					module.setModuleAct(bean.getModuleAct());
					moduleCategory.getModules().add(module);
					
					categoryMenuMap.put(moduleCotegoryCode, moduleCategory);
				}
				
			}
			
			for(String key:categoryMenuMap.keySet()){
				moduleCategoryList.add(categoryMenuMap.get(key));
			}
			
		} catch (DaoException e) {
			logger.error(e.getMessage(),e);
			throw new ServiceException("查询菜单和模块功能失败(权限)！");
		}
		   
		return moduleCategoryList;
	}

	@Override
	public List<MerchantModuleRight> queryOpertorPowerList(String accountNo,String type)
			throws ServiceException {
		List<MerchantModuleRight> moduleList=new ArrayList<MerchantModuleRight>();
		
		try {
			//获取到操作员所拥有的所有权限
			moduleList=powerInfoDao.queryModuleTellerByNo(accountNo,type);
		} catch (DaoException e) {
			throw new ServiceException("获取操作员权限失败！");
		}
		return moduleList;
	}

	

	@Override
	public Operators queryByAccountNo(String AccountNo) throws ServiceException {
		// TODO Auto-generated method stub
		
		Operators operator;
		try{
			operator=powerInfoDao.queryByAccountNo(AccountNo);
			
		}catch(DaoException e){
			throw new ServiceException("查询失败");
		}
		return operator;
	}

	@Override
	public Operators loadOperatorsById(long id) throws ServiceException {
		// TODO Auto-generated method stub
		Operators operator;
		try{
			operator=(Operators)powerInfoDao.loadById(id, Operators.class);
			
		}catch(DaoException e){
			
			throw new ServiceException("查询操作员失败");
		}
		return operator;
	}

	@Override
	public void auditingOperator(Operators auditedOper, String operators,
			AuditingItem auditingItem) throws ServiceException {
		
		try {
			Operators oper=(Operators)powerInfoDao.loadById(auditedOper.getId(), Operators.class);
			if(oper==null){
				throw new ServiceException("操作员不存在，请确认");
			}
			if(AuditingResultCodeType.PASS.getCode().equals(auditingItem.getResult_code())){
				oper.setStatus(OperatorsStatus.OK.getCode());
				
				String password = Utils.getpass(10);
				oper.setPwd(MD5Utils.MD5Encode(password));
				Date cDate = new Date();
				String cStr = DateFormatUtils.format(cDate, "yyyyMMdd");
				oper.setUpdatePWD(cStr);
				
				
				//业务员的话直接增加几个初始权限
				if(Role.AGENT_BUSS.getCode().equals(oper.getRoleType())){
					for (int i = 0; i < 3; i++) {
						MerchantModuleRight  mmr= new MerchantModuleRight();
						mmr.setMerchantNo(oper.getAccountNo());
						mmr.setOperators(oper.getAccountNo());
						if(i==0){
							mmr.setModuleCode(MerinfoModule.C_02_M_02.getName());//商户查询
						}else if(i==1){
							mmr.setModuleCode("C_02_M_01");//特约商户申请
						}else if(i==2){
							mmr.setModuleCode("C_07_M_04");//终端SN查询
						}
						baseDao.editSave(mmr);
					}
				}
			
				
				//把密码发送给客户。
				MessageSend messSend = new MessageSend();
				messSend.setPhoneNumber(oper.getMobile());
				messSend.setMesContent("尊敬的用户：您好，您在我司pos运营管理平台的账号是："+oper.getAccountNo()+",密码为："+password+",访问地址为：http://140.207.82.206:8090/fmposm");
				messSend.setSendFlag("0");
				Date date = new Date();
				messSend.setDtCreate(date);
				messSend.setDtLastmod(date);
				baseDao.editSave(messSend);
			}else if(AuditingResultCodeType.REFUSE.getCode().equals(auditingItem.getResult_code())){
				oper.setStatus(OperatorsStatus.REFUSED.getCode());
				
			}else{
				oper.setStatus(OperatorsStatus.INCOMPLETE_INFO.getCode());
				
			}
			oper.setDtCreate(new Date());
			
			
			
			
			powerInfoDao.editUpdate(oper);
			auditingItem.setAudit_code(AuditingType.OPERATORS_AUDITING.getCode());
			auditingItem.setAudit_name(AuditingType.OPERATORS_AUDITING.getName());
			auditingItem.setOperators(operators);
			auditingItemDao.editSave(auditingItem);
			powerInfoDao.addSyslog(SysLogType.OPERATORS_AUDITING.getCode(), SysLogType.OPERATORS_AUDITING.getName(), operators, operators+"对操作员【"+oper.getAccountNo()+"】进行审核");
		} catch (DaoException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new ServiceException("操作员审核出错");
		}
		
	}

	@Override
	public boolean updateStatus(Long id, String status,String loginOper)
			throws ServiceException {
		// TODO Auto-generated method stub
		
		
		try{
			if(id==0){
				throw new ServiceException("请选择要恢复或注销的操作员");
			}
	
			Operators oper=(Operators)powerInfoDao.loadById(id, Operators.class);
			oper.setStatus(status);
			powerInfoDao.editUpdate(oper);
			
			if(status.equals("00")){
				powerInfoDao.addSyslog(SysLogType.OPERATORS_RECOVER.getCode(), SysLogType.OPERATORS_RECOVER.getName(), loginOper, loginOper+"恢复了"+oper.getAccountNo()+"操作员");
			}else{
				powerInfoDao.addSyslog(SysLogType.OPERATORS_CANCEL.getCode(), SysLogType.OPERATORS_CANCEL.getName(), loginOper, loginOper+"注销了"+oper.getAccountNo()+"操作员");

			}
			
		}catch(DaoException e){
			e.printStackTrace();
			throw new ServiceException("操作员恢复或注销失败！");
			
		}
		
		return true;
	}

	@Override
	public int updateValitTime(List<Long> idList, String loginOper)
			throws ServiceException {
		// TODO Auto-generated method stub
		int total=0;
		
		try{
			if(idList.size()==0||idList==null){
				throw new ServiceException("请选择要恢复或注销的用户");
			}
			for(Long id:idList){
				Operators oper=(Operators)powerInfoDao.loadById(id, Operators.class);
				String oldDate=oper.getValidEndDate();
				DateFormat df=DateFormat.ZH_DEL_ALL;
				Date newDate=df.toDate(oldDate);
		        newDate.setYear(newDate.getYear()+1);
				oper.setValidEndDate(df.toString(newDate));
				powerInfoDao.editUpdate(oper);
				total++;
			}
			powerInfoDao.addSyslog(SysLogType.OPERATORS_DELAY_DATE.getCode(), SysLogType.OPERATORS_DELAY_DATE.getName(), loginOper, loginOper+"延长有效时间用户【"+total+"】个");
			
		}catch(DaoException e){
			e.printStackTrace();
			throw new ServiceException("更改操作员有效期失败");
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return total;
	}

	@Override
	public boolean editUpdateOperator(Operators oper, String loginOper)
			throws ServiceException {
		try{
	    	powerInfoDao.editUpdate(oper);
	    	List<OperRole> deleteList = queryOperRoleByAgentId(oper.getId());
    		for(OperRole operRole:deleteList){
    			baseDao.delete(operRole);
    		}
	    	if(StringUtils.isNotEmpty(oper.getAreaIdRole())&&oper.getAreaIdRole().equals("-1")){
				List<TblOrgMain> list = agentService.queryOrgMainListByOrg();
				for(TblOrgMain operatorsR:list){
					OperRole operRole = new OperRole();
					operRole.setAreaCode(operatorsR.getAreaId());
					operRole.setInsCode(operatorsR.getSuperId());
					operRole.setAgentId(operatorsR.getOrg_code());
					operRole.setCreDate(DateTime.getNow("yyyyMMddHHmmss"));
					operRole.setStatus("00");
					operRole.setOperId(String.valueOf(oper.getId()));
					baseDao.editSave(operRole);
				}
			}else{
				if(oper.getOperRoleList()!=null&&oper.getOperRoleList().size()>0){
					List<OperRole> operRoles = new ArrayList<OperRole>();
					operRoles = oper.getOperRoleList();
					for(OperRole operRole:operRoles){
						operRole.setCreDate(DateTime.getNow("yyyyMMddHHmmss"));
						operRole.setStatus("00");
						operRole.setOperId(String.valueOf(oper.getId()));
						baseDao.editSave(operRole);
					}
				}
			}
	    	powerInfoDao.addSyslog(SysLogType.OPERATORS_UPDATE.getCode(), SysLogType.OPERATORS_UPDATE.getName(), loginOper, loginOper+"修改【"+oper.getAccountNo()+"】信息成功");
		}catch(DaoException e){
			e.printStackTrace();
			throw new ServiceException("更新操作员信息失败！");
		}
		return true;
	}

	@Override
	public boolean resetPwd(Operators oper, Long id) throws ServiceException {
		// TODO Auto-generated method stub
		try{
			Operators tempOper=(Operators) powerInfoDao.loadById(id, Operators.class);
			if(tempOper==null){
				throw new ServiceException("该用户不存在");
			}
			
			String mobile=tempOper.getMobile();
			
			//String password = Utils.getpass(10);
			String password="123456";
			tempOper.setPwd(MD5Utils.MD5Encode(password));
			tempOper.setDtLostmod(new Date());
			String time = "";
			Date dt = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			time = sdf.format(dt);
			tempOper.setUpdatePWD(time);
			tempOper.setPwdErrTimes(0);
			powerInfoDao.editSave(tempOper);
			powerInfoDao.addSyslog(SysLogType.OPERATORS_RESETPWD.getCode(), SysLogType.OPERATORS_RESETPWD.getName(), oper.getAccountNo(), oper.getAccountNo()+"重置【"+tempOper.getAccountNo()+"】用户密码成功");
			
			//把密码发送给客户。
//			MessageSend messSend = new MessageSend();
//			messSend.setPhoneNumber(mobile);
//			messSend.setMesContent("您的密码重置成功，请牢记您的密码："+password+"。");
//			messSend.setSendFlag("0");
//			Date date = new Date();
//			messSend.setDtCreate(date);
//			messSend.setDtLastmod(date);
//			
//			baseDao.editSave(messSend);
			
			
		}catch(DaoException e){
			e.printStackTrace();
			throw new ServiceException("重置密码失败！");
		}
		return true;
	}

	@Override
	public Operators validateAccount(String AccountNo) throws ServiceException {
		Operators ops=null;
		try {
			Object[] params1 = {AccountNo};
			ops = (Operators) pageDao
					.createQueryUniqueResult("from Operators o where o.accountNo=?",params1);
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("验证登陆账号错误!!!");
		}
		return ops;
	}


	@Override
	public List<Operators> queryRealNameInfoByName(String realName , String orgCode, String roleType, int flag) throws ServiceException {
		List<Operators> ops=null;
		try {
			realName = "%" + realName + "%";
			ops = powerInfoDao.queryRealNameInfoByName(realName, orgCode, roleType, flag);
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询代理商名称失败！");
		}
		return ops;
	}


	@Override
	public Map<String, Map<String, String>> querySnCount( Long opId ) throws ServiceException {
		List<Object> list = new ArrayList<Object>();
		Map<String, Map<String, String>> infoMap = new HashMap<String, Map<String, String>>();
		Map<String, String> contextMap = new HashMap<String, String>();
		try {
			list = powerInfoDao.selSnCount(opId);
			if ( null != list && 0 < list.size() ) { 
					Iterator<Object> iterator = list.iterator();
					
					while(iterator.hasNext()) {	
						Object[] obj = (Object[]) iterator.next();
						
						contextMap = new HashMap<String, String>();
						contextMap.put("agentName", obj[1].toString());	
						contextMap.put("allNum", obj[2].toString());
						contextMap.put("companyName", null != obj[3] ? obj[3].toString() : "");
						contextMap.put("oneAgentName", null != obj[4] ? obj[4].toString() : "");
						contextMap.put("count", "0" );			
	
						infoMap.put( obj[0].toString(), contextMap);
				}
				
			}
			
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询仓库导入的SN数量失败！");
		}
		return infoMap;
	}
	


	@Override
	public Map<String, Map<String, String>> querySelfSupportSnCount( Long opId , String orgCode) throws ServiceException {
		List<Object> list = new ArrayList<Object>();
		Map<String, Map<String, String>> infoMap = new HashMap<String, Map<String, String>>();
		Map<String, String> contextMap = new HashMap<String, String>();
		try {
			list = powerInfoDao.selSelfSupportSnCount(opId , orgCode);
			if ( null != list && 0 < list.size() ) { 
					Iterator<Object> iterator = list.iterator();
					
					while(iterator.hasNext()) {	
						Object[] obj = (Object[]) iterator.next();
						
						contextMap = new HashMap<String, String>();
						contextMap.put("agentName", obj[1].toString());	
						contextMap.put("allNum", obj[2].toString());
						contextMap.put("companyName", null != obj[3] ? obj[3].toString() : "");
						contextMap.put("oneAgentName", null != obj[4] ? obj[4].toString() : "");
						contextMap.put("count", "0" );			
	
						infoMap.put( obj[0].toString(), contextMap);
				}
				
			}
			
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询自营导入的SN数量失败！");
		}
		return infoMap;
	}


	@Override
	public boolean queryOperatorInfoByNumberCode ( String agentType , String agentNumber ) throws ServiceException {
		
		boolean flag = false;
	
		try {
			flag = powerInfoDao.selOperatorInfoByNumberCode(agentType, agentNumber) ;
			
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询操作员信息失败！");
		}
		return flag;
	}

	@Override
	public String queryAgentNumberByAreaId(String areaId) throws ServiceException {
		String agentNumber = "";

		try {
			agentNumber = powerInfoDao.selAgentNumberByAreaId( areaId) ;
			
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询分公司序号信息失败！");
		}
		return agentNumber;
	}



	@Override
	public List<TblArea> queryAreaInfoByOrgCode( String orgCode ) throws ServiceException {
		List<TblArea> arealist = new ArrayList<TblArea>();
		List<Object> objList = new ArrayList<Object>();
		
		try {
			objList = powerInfoDao.selAreaInfoByOrgCode(orgCode);

			if (objList != null && objList.size() > 0) {
				Iterator<?> iterator = objList.iterator();
				while (iterator.hasNext()) {
					TblArea areaBean = new TblArea();
					Object[] obj = (Object[]) iterator.next();
					areaBean.setId( Long.valueOf( obj[0].toString() ) );
					areaBean.setName( obj[1].toString() );
					areaBean.setInsCode( obj[2].toString() );
					areaBean.setRemark1( ( null != obj[3] ? obj[3].toString() : "") );
					arealist.add(areaBean);
				}
			}
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询某机构下分公司属性信息失败！");
		}
		return arealist;
	}
	
	/**
	 *根据操作员id得到上级角色
	 * */
	@Override
	public String querySuperRoleByOpId(Long opId) throws DaoException {
		String SuperRole ="";
		try {
			
			String sql="select o1.role_type  from T_OPERATORS o1 where o1.id="+opId;
			
	    	SuperRole = (String)baseDao.createSQLQueryUniqueResult(sql);
		} catch (HibernateException e) {
			e.printStackTrace();
			logger.debug(e.getMessage(), e);
			throw new DaoException("查询操作员权限出错!");
		}
		return SuperRole;
	}


	@Override
	public Operators queryOperByOneOrgCode(String oneOrgCode) throws ServiceException {
		Operators ops=null;
		try {
			Long id=Long.valueOf(oneOrgCode);
			Object[] params1 = {id};
			ops = (Operators) pageDao
					.createQueryUniqueResult("from Operators o where o.id=?",params1);
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("通过一级机构查询机构管理员信息错误!!!");
		}
		return ops;
	}

	@Override
	//查询所有机构管理员 type 为 02
	public List<Operators> queryManagerInfoBySupId(String supId) throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		List<Object> objList = new ArrayList<Object>();
		
		try {
			objList = powerInfoDao.selManagerInfoBySupId(supId);
			
			if (objList != null && objList.size() > 0) {
				Iterator<?> iterator = objList.iterator();
				while (iterator.hasNext()) {
					Operators merchant = new Operators();
					Object[] obj = (Object[]) iterator.next();
					merchant.setId(((BigDecimal) obj[0]).longValue());
					merchant.setAccountNo((String) obj[1]);
					merchant.setRealName((String) obj[2]);
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.error(e.getMessage(), e);
			throw new ServiceException(e.getMessage());
		}
		return merchants;
	}
	/**
	 * 登录人员角色判定
	 * @param supId,roleType,opId
	 * @return
	 * @throws ServiceException
	 * @throws DaoException 
	 */
	public Map<String, String>  queryRealIdByOpId(Long supId, String roleType, Long opId,String orgCode) throws  DaoException {
		//上级角色
		String superRole="";
		String opId1;
		String groupCd="";
		Map<String, String> map=new HashMap<String, String>();
		try {
			
			//运营人员直属上级判定
			if(roleType.equals(Role.CLEAR_OPERATORS.getCode())||roleType.equals(Role.CLEAR_LEAD.getCode())||
				roleType.equals(Role.FINANCE_COMM.getCode())||roleType.equals(Role.FINANCE_LEAD.getCode())
				||roleType.equals(Role.OPERATORS_COMM.getCode())||roleType.equals(Role.OPERATORS_LEAD.getCode())
				||roleType.equals(Role.RISK_CONTROL_OPERATORS.getCode())||roleType.equals(Role.RISK_CONTROL_LEAD.getCode())
				||roleType.equals(Role.WARE_HOUSE_LEAD.getCode())){
				superRole=querySuperRoleByOpId(supId);
				opId1=supId.toString();
			}else{
				superRole=roleType;
				opId1=opId.toString();//当前操作人员
			}
			//受理市场运营增加受理市场标识
			if (roleType.equals(Role.OPERATORS_LEAD.getCode()))
			groupCd="2";
			map.put("orgCode", orgCode);
			map.put("superRole", superRole);
			map.put("opRealId", opId1);
			map.put("groupCd", groupCd);
		} catch (DaoException e) {
			logger.debug(e.getMessage(), e);
			throw new DaoException("查询操作员权限出错!");
		}
		return map;
	}

	@Override
	public List<TblOrgMain> queryOrgMinByAgentId(Long id)
			throws ServiceException {
		List<TblOrgMain> operatorList = new ArrayList<TblOrgMain>();
		try {
			List<?> lists = new ArrayList();
			Object[] params = {String.valueOf(id)};
			lists = pageDao.queryAll("from TblOrgMain p where p.status=1 and p.org_code in (select t.agentId from OperRole t where t.operId=?) and p.superId=48502000", params);
			if(null != lists && lists.size() > 0){
				for (Object object : lists) {
					TblOrgMain operators = (TblOrgMain)object;
					operatorList.add(operators);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######市场人员管理机构查询失败######", e);
		}
		return operatorList;
	}

	@Override
	public List<TblOrgMain> queryNoOrgMinByAgentId(Long id,String areaId)
			throws ServiceException {
		List<TblOrgMain> operatorList = new ArrayList<TblOrgMain>();
		try {
			List<?> lists = new ArrayList();
			Object[] params = {String.valueOf(id),areaId};
			lists = pageDao.queryAll("from TblOrgMain p where p.status=1 and p.org_code not in (select t.agentId from OperRole t where t.operId=?) and p.areaId=? and p.superId=48502000 order by p.id desc", params);
			if(null != lists && lists.size() > 0){
				for (Object object : lists) {
					TblOrgMain operators = (TblOrgMain)object;
					operatorList.add(operators);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######市场人员管理未机构查询失败######", e);
		}
		return operatorList;
	}
	
	private List<OperRole> queryOperRoleByAgentId(Long id)
			throws ServiceException {
		List<OperRole> operatorList = new ArrayList<OperRole>();
		try {
			List<?> lists = new ArrayList();
			Object[] params = {String.valueOf(id)};
			lists = pageDao.queryAll("from OperRole t where t.operId=?", params);
			if(null != lists && lists.size() > 0){
				for (Object object : lists) {
					OperRole operators = (OperRole)object;
					operatorList.add(operators);
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("######市场人员管理机构查询失败######", e);
		}
		return operatorList;
	}
	
	
	public Operators queryYyAgentId(Long id) throws ServiceException {
		Operators ops=null;
		try {
			Object[] params1 = {id};
			ops = (Operators) pageDao
					.createQueryUniqueResult("from Operators o where id=?",params1);
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询运维人员上级代理商失败!!!");
		}
		return ops;
	}

	@Override
	public List<Operators> queryOperatorsByParams(String roleType, String oneagentId) throws ServiceException {
		List<Operators> merchants = new ArrayList<Operators>();
		List<Object> objList = new ArrayList<Object>();
		try {
			objList = powerInfoDao.queryOperatorsByParams(roleType, oneagentId);
			if(objList != null && objList.size() > 0){
				Iterator<?> iterator = objList.iterator();
				while (iterator.hasNext()) {
					Operators merchant = new Operators();
					Object[] obj = (Object[]) iterator.next();
					merchant.setId(((BigDecimal) obj[0]).longValue());
					merchant.setRealName((String) obj[2]);
					merchants.add(merchant);
				}
			}
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("加载所属机构失败！");
		}
		return merchants;
	}

	@Override
	public Operators findDirectlyUnder(Long id) throws ServiceException {
		Operators ops=null;
		try {
			Object[] params1 = {id};
			ops = (Operators) pageDao
					.createQueryUniqueResult("from Operators o where id=? and superiorId=40001 and roleType='02' and groupCd='2'",params1);
		} catch (DaoException e) {
			e.printStackTrace();
			throw new ServiceException("查询运维人员上级代理商失败!!!");
		}
		return ops;
	}
	

}
